<?php
if (! defined ( 'APP_PATH' ))
	die ( 'Load Error. <br />Classfied Load File can not accessed directly' );
	/*
	 * Database Extension Class for Classified Site
	 * 
	 */

class DB {
	static $instance;
	private $con;
	private $stmt;
	public static function newInstance() {
		if (! self::$instance instanceof self) {
			self::$instance = new self ();
		}
		return self::$instance;
	}
	
	public function __construct() {
		
		$dsn = 'mysql:dbname=' . DB_DATABASE . ';host=' . DB_SERVER;
		try {
			$this->con = new PDO ( $dsn, DB_USER, DB_PASSWORD );
		} catch ( PDOException $e ) {
			echo $e->getMessage ();
		}
		$this->stmt = new PDOStatement ();
	
	}
	
	public function update($sql,$params=array()){
		$this->stmt = $this->con->prepare ( $sql );
		return $this->stmt->execute ( $params );
		
	}
	public function delete($sql,$params=array()){
		$this->stmt = $this->con->prepare ( $sql );
		return $this->stmt->execute ( $params );
		
	}
        
        
	
	public function insert($sql,$params=array()){
		$this->stmt = $this->con->prepare ( $sql );
		return $this->stmt->execute ( $params );
		
	}
	
	public function query($sql, $params = array()) {
		
		$this->stmt = $this->con->prepare ( $sql );
		$this->stmt->execute ( $params );
		return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
	}
	public function queryString() {
		if ($this->stmt) {
			return $this->stmt->queryString;
		}
	}
        
        public function beginTrans(){
            $this->con->beginTransaction();
        }
        
        public function commit(){
            $this->con->commit();
        }
        
        public function rollback(){
            $this->con->rollBack();
        }
	
	public function rowCount(){
		if($this->stmt){
			return $this->stmt->rowCount();
		}
	}
	public function last_insert_id(){
		return $this->con->lastInsertId();
	}
	public function fetchAll($type='assoc'){
		if($this->stmt){
			if($type=='assoc'){
				return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
			}else{
				return $this->stmt->fetchAll(PDO::FETCH_NUM);
			}
		}
		
	}
	
	
}